#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2e5 + 5;

int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int bfs(string s, string t) {
  unordered_map<string, int> dis;
  queue<string> q;
  q.push(s);
  dis[s] = 0;
  if (s == t) return 0;
  while (q.size()) {
    string now = q.front();
    q.pop();
    int d = dis[now];
    int id = now.find('0');
    int x = id / 3, y = id % 3;
    rep(i, 0, 3) {
      int xx = x + dx[i], yy = y + dy[i];
      if (xx < 0 || xx > 2 || yy < 0 || yy > 2) continue;
      int id2 = xx * 3 + yy;
      string nxt = now;
      swap(nxt[id], nxt[id2]);
      if (dis.count(nxt)) continue;
      if (nxt == t) return d + 1;
      q.push(nxt);
      dis[nxt] = d + 1;
    }
  }
  return -1;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  string s;
  cin >> s;
  string t = "123804765";
  cout << bfs(s, t);
  return 0;
}